﻿namespace SsisLdapSource
{
    using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
    using System;
    using System.Linq;

    public partial class SsisLdapSource 
    {
        private void ValidateColumns()
        {
            IsListOfAttributesToLoadUnique();
            DoesEachSuppliedActiveDirectoryAttributeHasOutputColumn();
        }

        private void IsListOfAttributesToLoadUnique()
        {
            var duplicates = (from x in AttributesToLoad
                              group x by x into g
                              let count = g.Count()
                              where count > 1
                              orderby count descending
                              select new { Value = g.Key, Count = count })
                             .ToList();

            if (duplicates.Any())
            {
                throw new Exception(string.Format(
                    "Duplicate value was detected in the AttributesToLoad property{0} ", duplicates[0].Value));
            }
        }

        private void DoesEachSuppliedActiveDirectoryAttributeHasOutputColumn()
        {
            var output = ComponentMetaData.OutputCollection[0];
            DoesNumberOfAttributesToLoadMatchTheNumberOfOutputColumns(output);
            DoAttributesToLoadNamesMatchOutputColumnNames(output);
        }

        private void DoesNumberOfAttributesToLoadMatchTheNumberOfOutputColumns(IDTSOutput100 output)
        {
            var numberOfOutputColumns =
                output.OutputColumnCollection.Count;
            var numberOfAttributesToLoad =
                AttributesToLoad.Length;

            if (numberOfAttributesToLoad != numberOfOutputColumns)
            {
                ReinitializeMetaData();
            }
        }

        private void DoAttributesToLoadNamesMatchOutputColumnNames(IDTSOutput100 output)
        {
            foreach (IDTSOutputColumn100 column in output.OutputColumnCollection)
            {
                if (!AttributesToLoad.Contains(column.Name))
                {
                    ReinitializeMetaData();
                }
            }
        }
    }
}
